<template>
<el-card class="box-card">
  <div slot="header" class="clearfix">
    <span v-if="this.$route.query.id">试题修改</span>
    <span v-else>试题录入</span>
  </div>
  <div class="text item">
    <!-- 学科下拉框 -->
    <el-form ref='ruleForm' :model="form" :rules="rules" label-width="120px">
      <el-form-item label="学科 :" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择" class="select" @change="changeSubject">
          <el-option v-for="(item, index) in subjects" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- 目录下拉框 -->
      <el-form-item label="目录 :" prop="catalogID">
        <el-select v-model="form.catalogID" placeholder="请选择" class="select">
          <el-option v-for="item in directorys" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- 企业下拉框 -->
      <el-form-item label="企业 :" prop="enterpriseID">
        <el-select v-model="form.enterpriseID" p laceholder="请选择" class="select">
          <el-option v-for="item in companys" :key="item.id" :label="item.company" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 城市下拉框 -->
      <el-form-item label="城市 :" prop="province">
        <el-select
          class="city"
          v-model="form.province"
          @keyup.enter="handleFilter"
          @change="handleProvince"
          filterable
          >
          <el-option
            v-for="item in citySelect.province"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <el-select
          class="city"
          v-model="form.city"
          @keyup.enter="handleFilter"
          filterable
        >
          <el-option
            v-for="item in citySelect.cityDate"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 方向的下拉框 -->
      <el-form-item label="方向 :" prop="direction">
        <el-select v-model="form.direction" placeholder="请选择" class="select">
          <el-option v-for="item in direction" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <!-- 题型的单选按钮组 -->
      <el-form-item label="题型 :" prop="questionType">
        <el-radio-group v-model="form.questionType">
          <el-radio v-for="item in questionType" :key="item.value" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 难度的单选按钮组 -->
      <el-form-item label="难度 :" prop="difficulty">
        <el-radio-group v-model="form.difficulty">
          <el-radio :label="item.value" v-for="item in difficulty" :key="item.value">{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 题干的下拉框 -->
      <el-form-item label="题干 :" prop="question" style="height:260px">
        <quill-editor v-model="form.question" style="height:200px;" :options="editorOption" />
      </el-form-item>
      <!-- 选项的下拉框 -->
      <el-form-item label="选项 :" prop="content" class="option_item" v-if="form.questionType === 1">
        <div class="option_item" style="width=2000px" v-for="(item, index) in option_items" :key="item.id">
          <el-radio-group v-model="radio">
            <el-radio :label="index" :checked="form.options[index].isRight" class="radioIndex">{{item}}：</el-radio>
          </el-radio-group>
          <el-input v-model="form.options[index].title" class="options"></el-input>&nbsp;
            <!--
            - action：必选参数，上传的地址：http://ttapi.research.itcast.cn/mp/v1_0/user/images
            - headers: 设置上传的请求头部。要携带token
            - name：上传的文件字段名。要与接口中要求保持一致。
            - show-file-list： 是否显示已上传文件列表
            - on-success：文件上传成功时的钩子。`function(response, file, fileList)`
            - before-upload: 上传之前对文件进行检测。
            -->
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="hSuccess"
            :before-upload="beforeAvatarUpload"
            style="width=100px;height=60px"
            @click.native="clickUpload(index)">
              <!-- 当上传成功之后，imageUrl就会有值，此时做预览
                给img设置了src后，显示图片内容的过程是异步的 ---- 并不是设了src后就可以立即看到图片的
                问：你怎么知道图片已经完成了加载？ -->
              <el-image v-if="url[index]" :src="url[index]" class="avatar" @load="hLoadUploadImage" />
              <span v-else class="avatar-uploader-span">上传图片</span>
              <i class="el-icon-circle-close"></i>
          </el-upload>
        </div>
        <el-button type="danger" :disabled="form.questionType === 1" v-if="form.questionType === 1">+增加选项与答案</el-button>
      </el-form-item>
      <el-form-item label="选项 :" prop="content" class="option_item" v-if="form.questionType === 2">
        <div class="option_item" v-for="(item,index) in option_items" :key="item.id">
          <el-checkbox :label="index" :checked="form.options[index].isRight" class="checkIndex">{{item}}：
            <!-- <el-input v-model="form.name" class="options"></el-input> -->
          </el-checkbox>
          <el-input v-model="form.options[index].title" class="options"></el-input>&nbsp;
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="hSuccess"
            :before-upload="beforeAvatarUpload"
            style="width=100px;height=60px"
            @click.native="clickUpload(index)">
              <!-- 当上传成功之后，imageUrl就会有值，此时做预览
                给img设置了src后，显示图片内容的过程是异步的 ---- 并不是设了src后就可以立即看到图片的
              -->
              <el-image v-if="url[index]" :src="url[index]" class="avatar" @load="hLoadUploadImage" />
              <!-- 没有上传之前，这里是一个大大的 + -->
              <span v-else class="avatar-uploader-span">上传图片</span>
              <i class="el-icon-circle-close"></i>
          </el-upload>
        </div>
        <el-button type="danger" @click="ascii">+增加选项与答案</el-button>
      </el-form-item>
      <el-form-item label="解析视频 :">
        <el-input v-model="form.videoURL"></el-input>
      </el-form-item>
      <el-form-item label="答案解析 :" prop="answer" style="height:260px">
          <quill-editor v-model="form.answer" style="height:200px" class="Text" :options="editorOption" />
      </el-form-item>
      <el-form-item label="题目备注 :">
        <el-input type="textarea" style="height:96px;width:400px" v-model="form.remarks"></el-input>
      </el-form-item>
      <el-form-item label="试题标签 :" style="width:400px">
        <el-select
          style="width:400px"
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择文章标签">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-if="this.$route.query.id" type="primary" @click="changeSubmit">确认修改</el-button>
        <el-button v-else type="primary" @click="onSubmit('formName')">确认提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple as simpleSubjects } from '@/api/hmmm/subjects.js'
import { simple as itemDirectorys } from '@/api/hmmm/directorys.js'
import { simple as itemTags } from '@/api/hmmm/tags.js'
import { list } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      rules: {
        subjectID: [
          { required: true, message: '请选择学科名称', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业名称', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'change' }
        ]
      },
      form: {
        titleRadio: ['', '', '', ''],
        titleCheck: ['', '', '', ''],
        subjectID: '',
        catalogID: '',
        direction: '',
        enterpriseID: '',
        remarks: '',
        difficulty: 1,
        questionType: 1,
        tags: [],
        answer: '',
        question: '',
        province: '',
        city: '',
        isRight: [],
        options: [
          { isRight: false, title: '' },
          { isRight: false, title: '' },
          { isRight: false, title: '' },
          { isRight: false, title: '' }
        ],
        videoURL: ''
      },
      index: '',
      option_items: ['A', 'B', 'C', 'D'],
      dialogVisible: false,
      requestParameters: {},
      subjects: [],
      directorys: [],
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      companys: [],
      citys: [],
      direction: direction,
      questionType: questionType,
      difficulty: difficulty,
      citySelect: {
        province: [],
        cityDate: []
      },
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      options: [],
      value: [],
      url: ['', '', '', ''],
      radio: ''
    }
  },
  created () {
    this.subjectLoad()
    this.companysLoad()
    this.getCityData()
    this.itemTagsLoad()
    if (this.$route.query.id) {
      this.getList(this.$route.query.id)
    }
  },
  mounted () {
    this.subjectLoad()
  },
  watch: {
    $route (to, from) {
      if (this.$route.query.id) {

      } else {
        // console.log(1)
        Object.assign(this.$data, this.$options.data())
        this.$nextTick(() => this.$refs.ruleForm.clearValidate())
        this.subjectLoad()
        this.companysLoad()
        this.getCityData()
        this.itemTagsLoad()
      }
    }
  },
  methods: {
    // 获取学科列表
    async subjectLoad () {
      try {
        const { data: res } = await simpleSubjects()
        console.log(res)
        this.subjects = res
        console.log(this.subjects[1].value)
      } catch (err) {
        console.log(err)
      }
    },
    // 获得目录列表
    async changeSubject (id) {
      try {
        const { data: res } = await itemDirectorys({ subjectID: id })
        this.directorys = res
        this.form.catalogID = ''
      } catch (err) {
        console.log(err)
      }
    },
    // 获取企业列表
    async companysLoad () {
      try {
        const { data: res } = await list()
        this.companys = res.items
      } catch (err) {
        console.log(err)
      }
    },
    async itemTagsLoad () {
      try {
        const { data: res } = await itemTags()
        this.options = res
        // console.log(this.companys)
      } catch (err) {
        console.log(err)
      }
    },
    // 获取省
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 选省获取到市
    handleProvince (e) {
      this.citySelect.cityDate = citys(e)
      // this.requestParameters.city = this.citySelect.cityDate[0]
      // 111
    },
    ascii () {
      const arrOption = this.option_items[this.option_items.length - 1]
      const ascii = arrOption.charCodeAt() + 1
      const code = String.fromCharCode(ascii)
      this.option_items.push(code)
      this.form.options.push({ code: '', title: '', isRight: false })
      this.url.push('')
    },
    optionsGet () {
      var options = []
      if (this.form.questionType === 1) {
        var radio = document.querySelectorAll('.radioIndex .el-radio__original')
        var radioItems = this.option_items
        var titleRadio = this.form.options
        var imgRadio = this.url
        radio.forEach(function (value, index) {
          var radio = { code: '', title: '', img: '', isRight: null }
          radio.isRight = value.checked
          radio.code = radioItems[index]
          radio.title = titleRadio[index].title
          radio.img = imgRadio[index]
          console.log(radio)
          options.push(radio)
        })
        console.log(radio)
        return options
      } else if (this.form.questionType === 2) {
        var checkBox = document.querySelectorAll('.checkIndex .el-checkbox__original')
        var checkItems = this.option_items
        var titleCheck = this.form.options
        var imgCheck = this.url
        checkBox.forEach(function (value, index) {
          var checkBox = { code: '', title: '', img: '', isRight: null }
          checkBox.isRight = value.checked
          checkBox.code = checkItems[index]
          checkBox.title = titleCheck[index].title
          checkBox.img = imgCheck[index]
          console.log(checkBox)
          options.push(checkBox)
        })
        return options
      }
    },
    // 提交发布
    async onSubmit () {
      var requstion = {}
      const subjectID = this.form.subjectID
      const catalogID = this.form.catalogID
      const enterpriseID = this.form.enterpriseID
      const province = this.form.province
      const city = this.form.city
      const direction = this.form.direction
      const questionType = this.form.questionType.toString()
      const difficulty = this.form.difficulty.toString()
      const question = this.form.question
      const videoURL = this.form.videoURL
      const answer = this.form.answer
      const remarks = this.form.remarks
      const tags = this.form.tags.join(',')
      const options = this.optionsGet()
      requstion = { subjectID, catalogID, enterpriseID, province, city, direction, questionType, difficulty, question, options, videoURL, answer, remarks, tags }
      console.log(requstion)
      try {
        const { data: res } = await add(requstion)
        this.$router.push('/questions/list')
        this.$message.success('添加成功')
        console.log(res)
      } catch (err) {
        console.log(err)
        this.$message.error('添加失败')
      }
    },
    hSuccess (res, file) {
      console.log('上传成功,从后端返回的数据是', res, file)
      this.$set(this.url, this.index, res.data.url)
      console.log(this.url)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    hLoadUploadImage () {
      console.log('我好了')
    },
    clickUpload (index) {
      this.index = index
      console.log(this.index)
    },
    async getList (id) {
      try {
        const { data: res } = await detail({ id })
        console.log(res)
        const resOptions = res.options
        const resTags = res.tags.split(',')
        resOptions.forEach(function (value, index) {
          if (value.isRight === 0) {
            value.isRight = false
          } else {
            value.isRight = true
          }
        })
        const optionsRadio = res.options
        console.log(optionsRadio)
        optionsRadio.forEach((value, index) => {
          if (value.isRight === true) {
            this.radio = index
          }
        })
        this.form = res
        console.log(this.form)
        console.log(Number(res.questionType))
        // this.form.questionType = Number(res.questionType)
        this.form.subjectID = res.subjectID
        this.form.catalogID = res.catalogID
        this.form.enterpriseID = res.enterpriseID
        this.form.province = res.province
        this.form.city = res.city
        this.form.direction = res.direction
        this.form.questionType = Number(res.questionType)
        this.form.tags = resTags
        this.difficulty.forEach((val, index) => {
          console.log(val)
          console.log(val.value)
          console.log(Number(res.difficulty))
          if (val.value === Number(res.difficulty)) {
            this.form.difficulty = val.value
            // console.log(diffValue)
          } else {
            console.log(res.difficulty)
            console.log(val.value)
          }
        })
        this.directorysGet()
      } catch (err) {
        console.log(err)
      }
    },
    async changeSubmit () {
      this.form.questionType = toString(this.form.questionType)
      this.form.tags = toString(this.form.tags)
      try {
        await update(this.form)
        // this.$message.success('我好了')
      } catch (err) {
        console.log(err)
      }
    },
    async directorysGet () {
      const subId = this.form.subjectID
      try {
        const { data: res } = await itemDirectorys({ subjectID: subId })
        this.directorys = res
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
  body {
    margin: 0;
    padding: 0;
}
.box-card {
  margin: 20px 20px 20px;
}
.el-card__body {
  padding: 20px;
}
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .select {
    width: 400px;
  }
  .city {
    width: 197px;
    margin-right: 6px;
  }
  .options {
    width: 240px;
  }
  .option_item {
    // overflow: hidden;
    // width: 1000px;
    padding-bottom: 20px;
    line-height: 1;
  }
  .option_item .el-radio {
    margin: 0;
  }
  .Text {
    height: 239px;
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    margin: 0;
    width: 100px;
    height: 60px;
    cursor: pointer;
    overflow: hidden;
    display: inline-block;
    vertical-align: middle;
    position: relative;
  }
  .el-icon-circle-close{
    position: absolute;
    top: 0px;
    right: 0px;
  }
  .avatar-uploader .el-upload {
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-span {
    font-size: 15px;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 60px;
    display: block;
  }
</style>
